#include "ConvertorManager.h"
#include "./Plugin/PluginException.h"
#include "./Plugin/Factory.h"
#include <SingletonHolder.h>

#ifdef _DEBUG
#include <iostream>
#endif

using namespace PluginSystem;
using namespace std;

ConvertorManager::ConvertorManager(std::vector<std::string> thePlugins)
{
	myPluginType = "convertor";

	for(size_t i=0; i < thePlugins.size(); i++ )
	{
		try
		{
			IConverter *_converter = (IConverter*)Factory::Instance()->Create(myPluginType,thePlugins[i]);
			if(_converter != NULL)
			{
#ifdef _DEBUG
				cout << _converter->Format();
#endif
				myPlugins.insert(pair<string,IConverter*>(_converter->Format(),_converter));
			}
		}
		catch (PluginSystem::PluginException &ex)
		{
			SingletonHolder::Instance().WriteEx(ex.what());
		}
	}
}

ConvertorManager::~ConvertorManager(void)
{
	LoadedPlugins::iterator _iter = myPlugins.begin();
	for(;_iter != myPlugins.end(); _iter++)
	{
		delete (*_iter).second;
	}
}


bool ConvertorManager::Load(std::string thePath)
{
	try
	{
		IConverter *_converter = (IConverter*)Factory::Instance()->Create(myPluginType,thePath);
		if(_converter)
		{
			myPlugins.insert(pair<string,IConverter*>(_converter->Format(),_converter));
			return true;
		}
	}
	catch (PluginSystem::PluginException &ex)
	{
		SingletonHolder::Instance().WriteEx(ex.what());
		return false;
	}

	return false;
}

IConverter* ConvertorManager::Get(std::string theFormat)
{
	LoadedPlugins::iterator _result = myPlugins.find(theFormat);
	if(_result != myPlugins.end())	// ak sa nerovna koncu tak sme nasli plugin pre taky format
		return (*_result).second;
	else
		return NULL;	
}

